package com.kt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kt.config.security.component.JwtTokenUtil;
import com.kt.mapper.AdminRoleMapper;
import com.kt.mapper.RoleMapper;
import com.kt.pojo.Admin;
import com.kt.mapper.AdminMapper;
import com.kt.pojo.AdminRole;
import com.kt.pojo.RespBean;
import com.kt.pojo.Role;
import com.kt.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kt.util.AdminUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author KamTeng
 * @since 2021-02-22
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Resource
    private UserDetailsService userDetailsService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Resource
    private AdminMapper adminMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private AdminRoleMapper adminRoleMapper;

    /**
     * 登录之后返回Token
     *
     * @param username
     * @param password
     * @param code
     * @param request
     * @return
     */
    @Override
    public RespBean login(String username, String password, String code, HttpServletRequest request) {
        // 验证码
        String captcha = (String) request.getSession().getAttribute("captcha");
        // 判断验证码
        if ("".equals(code) || !captcha.equalsIgnoreCase(code)) {
            return RespBean.error("验证码输入有误，请重新输入！");
        }
        // 获取UserDetails
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        // 判断用户是否被禁用
        if (userDetails.isEnabled()) {
            // 前端获取的密码通过passwordEncoder与数据库中的密码对比
            if (userDetails != null && passwordEncoder.matches(password, userDetails.getPassword())) {
                // 更新security登录用户对象
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                // 将authenticationToken放入spring security全局中
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                // 生成Token
                String token = jwtTokenUtil.generateToken(userDetails);
                // 将token和头部信息存入map中，登录成功后带给前端。
                HashMap<String, String> tokenMap = new HashMap<>();
                tokenMap.put("token", token);
                tokenMap.put("tokenHead", tokenHead);
                return RespBean.success("登录成功", tokenMap);
            }
            return RespBean.error("用户名或密码错误");
        }
        return RespBean.error("该账号也被禁用,请联系管理员!");
    }

    /**
     * 根据用户名获取用户
     *
     * @param username
     * @return
     */
    @Override
    public Admin getAdminByUserName(String username) {
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username", username).eq("enabled", true));
    }

    /**
     * 根据用户id查询角色列表
     * @param adminId
     * @return
     */
    @Override
    public List<Role> getRoles(Integer adminId) {
        return roleMapper.getRoles(adminId);
    }

    /**
     * 获取所有操作员
     * @param keywords
     * @return
     */
    @Override
    public List<Admin> getAllAdmins(String keywords) {
        return adminMapper.getAllAdmins(AdminUtils.getCurrentAdmin().getId(), keywords);
    }

    /**
     * 更新操作员角色
     * @param adminId
     * @param rids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RespBean updateAdminRole(Integer adminId, Integer[] rids) {
        adminRoleMapper.delete(new QueryWrapper<AdminRole>().eq("adminId", adminId));
        Integer result = adminRoleMapper.updateAdminRole(adminId, rids);
        if (rids.length == result) {
            return RespBean.success("更新成功！");
        }
        return RespBean.error("更新失败！");
    }

    /**
     * 更新用户密码
     * @param oldPwd
     * @param pwd
     * @param adminId
     * @return
     */
    @Override
    public RespBean updateAdminPwd(String oldPwd, String pwd, Integer adminId) {
        Admin admin = adminMapper.selectById(adminId);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        // 判断旧密码是否正确
        if (encoder.matches(oldPwd, admin.getPassword())) {
            admin.setPassword(encoder.encode(pwd));
            int result = adminMapper.updateById(admin);
            if (1 == result) {
                return null;
            }
        }
        return RespBean.error("更新失败");
    }

}
